import React, { Component } from "react";

class Child extends Component {
  state = {
    count: 10,
    prevCount: 10,
  };
  // 根据props的值，去生成一个新的state
  // 前面要加static
  // 必须要有state，return一个对象或者null
  static getDerivedStateFromProps(nextProps, nextState) {
    console.log("getDerivedStateFromProps");
    // return null;
    // return {
    //   count: nextProps.num,
    // };

    if (nextProps.num === nextState.prevCount) {
      return null;
    } else {
      return {
        count: nextProps.num,
        prevCount: nextProps.num,
      };
    }
    // 1. count: 10, prevCount: 10,
    // 2. nextProps.num 20   nextState.prevCount 10    ->   count 20  prevCount: 20
    // 3. nextProps.num 40   nextState.prevCount 20    ->   count 40  prevCount: 40
    // 4. nextProps.num 40   nextState.prevCount 40    ->   null
  }
  render() {
    return <div>child组件 - {this.state.count}</div>;
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({
        count: 80,
      });
    }, 4000);
  }

  // getSnapshotBeforeUpdate在更新之前得到一个快照
  // 要配合componentDidUpdate一起用，还必须有return
  getSnapshotBeforeUpdate(prevProps, precState) {
    console.log("getSnapshotBeforeUpdate");
    // 只有dom的样式和componentDidUpdate得到的是不一样的
    return 5;
  }
  componentDidUpdate(prevProps, precState, snapshot) {
    console.log("componentDidUpdate");
    console.log(snapshot);
  }
}

export default Child;
